package com.hn.common.utils.ding;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiServiceGetCorpTokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiServiceGetCorpTokenResponse;
import com.taobao.api.ApiException;

/**
 * 获取access_token工具类
 *
 * @author admin
 */
public class AccessTokenUtil {

    // 企业内部应用获取token
   public static String getToken() {
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(DingURLConstant.URL_GET_TOKKEN);
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(DingConstant.APPKEY);
            request.setAppsecret(DingConstant.APPSECRET);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            String accessToken = response.getAccessToken();
            return accessToken;
        } catch (ApiException e) {
            throw new RuntimeException("ApiException:"+e.getErrMsg());
        }
    }


    /*public static String getToken() {
        return getToken(DingConstant.CORP_ID);
    }*/

    /**
     * 第三方企业应用获取token
     *
     * @param corpid 企业ID
     * @return
     */
    public static String getToken(String corpid) {
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/service/get_corp_token");
        OapiServiceGetCorpTokenRequest req = new OapiServiceGetCorpTokenRequest();
        req.setAuthCorpid(corpid);
        try {
            // todo suiteTicket 测试应用不用传
            OapiServiceGetCorpTokenResponse execute = client.execute(req,
                    DingConstant.APPKEY, DingConstant.APPSECRET,
                    "");
            return execute.getAccessToken();
        } catch (Exception e) {

        }
        return null;
    }
}
